package com.baoyouqun.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.cola.dto.Response;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baoyouqun.domain.cmd.UserRoleCmd;
import com.baoyouqun.entity.UserRole;
import com.baoyouqun.mapper.UserRoleMapper;
import com.baoyouqun.service.UserRoleService;
import jakarta.annotation.Resource;
import org.apache.poi.util.StringUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements UserRoleService {

    @Resource
    private UserRoleMapper userRoleMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Response assignRoles(UserRoleCmd cmd) {
        if (!StringUtil.isBlank(cmd.getUserId())) {
            return Response.buildFailure("100301", "用户ID不能为空");
        }
        if (CollUtil.isEmpty(cmd.getRoleIds())) {
            return Response.buildFailure("100301", "角色ID列表不能为空");
        }

        // 先删除该用户的所有角色
        deleteByUserId(cmd.getUserId());

        // 批量添加新角色
        List<UserRole> userRoles = cmd.getRoleIds().stream().map(roleId -> {
            UserRole userRole = new UserRole();
            userRole.setUserId(cmd.getUserId());
            userRole.setRoleId(roleId);
            return userRole;
        }).collect(Collectors.toList());

        boolean result = saveBatch(userRoles);
        return result ? Response.buildSuccess() : Response.buildFailure("100310", "分配角色失败");
    }

    @Override
    public List<String> selectByUserId(String userId) {
        if (StringUtil.isBlank(userId)) {
            return new ArrayList<>();
        }
        List<UserRole> list = list(
                new LambdaQueryWrapper<UserRole>()
                        .eq(UserRole::getUserId, userId)
        );
        return list.stream().map(UserRole::getRoleId).collect(Collectors.toList());
    }

    public void deleteByUserId(String userId) {
        if (StringUtil.isBlank(userId)) {
            return;
        }
        remove(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, userId));
    }


    // UserRoleServiceImpl.java 实现新增方法
    @Override
    public Map<String, List<String>> selectByUserIds(List<String> userIds) {
        if (CollUtil.isEmpty(userIds)) {
            return new HashMap<>();
        }
        // 批量查询所有用户的角色关联记录
        List<UserRole> userRoles = list(
                new LambdaQueryWrapper<UserRole>()
                        .in(UserRole::getUserId, userIds)
        );
        // 按用户ID分组，收集角色ID列表
        return userRoles.stream()
                .collect(Collectors.groupingBy(
                        UserRole::getUserId,
                        Collectors.mapping(UserRole::getRoleId, Collectors.toList())
                ));
    }

    @Override
    public String getRoleIdByUserId(String userId) {
        UserRole userRoles = getOne(
                new LambdaQueryWrapper<UserRole>()
                        .eq(UserRole::getUserId, userId)
                        .last("limit 1")
        );
        // 按用户ID分组，收集角色ID列表
        if (userRoles == null) {
            return null;
        }
        return userRoles.getRoleId();
    }
}